package util

import (
	"time"

	"github.com/dgrijalva/jwt-go"
)

// 生成token
func CreateToken(uid, secret string) (string, error) {
	at := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"id":  uid,
		"exp": time.Now().Add(time.Minute * 3600).Unix(),
	})

	token, err := at.SignedString([]byte(secret))
	if err != nil {
		return "", err
	}

	return token, nil
}

func ParseToken(token string, secret string) (jwt.MapClaims, error) {
	claim, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte("hongsi"), nil
	})

	if err != nil {
		emptyClaims := jwt.MapClaims{}
		return emptyClaims, err
	}

	items := claim.Claims.(jwt.MapClaims)
	return items, nil
}
